<template>
  <view class="home-container">
    <!-- 顶部地址栏 -->
    <view class="top-bar">
      <text class="location">黄浦区上海市人民政府(人民大道...)</text>
      <view class="top-icons">
        <text class="iconfont">&#xe6b8;</text>
        <text class="iconfont">&#xe60b;</text>
      </view>
    </view>
    <!-- 搜索栏 -->
    <view class="search-bar" @click="goToSearch">
      <input class="search-input" placeholder="点击搜索商品"  @click="goToSearch" />
      <button class="search-btn" @click="goToSearch">搜索</button>
      <text class="member-code">会员码</text>
    </view>
    <!-- 轮播图 -->
    <view class="swiper-box">
      <swiper
        class="swiper"
        circular
        autoplay
        interval="3000"
        duration="500"
        indicator-dots
      >
        <swiper-item v-for="(img, idx) in bannerList" :key="idx">
          <image class="swiper-img" :src="img" mode="aspectFill" />
        </swiper-item>
      </swiper>
    </view>
    <!-- 分类入口，动态渲染 -->
    <view class="category-list">
      <view
        class="category-item"
        v-for="(item, idx) in categories"
        :key="item.id"
        @click="onCategoryClick(item)"
      >
        <image :src="item.categoryIcon" class="category-img" />
        <text class="category-text">{{ item.categoryName}}</text>
      </view>
<!-- 手动添加领券中心入口 -->
	<view class="category-item" @click="goToCouponCenter()">
	  <image src="/static/images/coupon-center.png" class="category-img" />
	  <text class="category-text">领券中心</text>
	</view>
    </view>
    <!-- banner 区域 -->
    <view class="banner-area">
      <image class="banner-img" src="/static/images/banner/seckill.gif" @click="toSecKill" mode="aspectFill" />
    </view>
    <!-- 夜宵专区 -->
    <view class="night-area">
      <image class="night-img" src="/static/images/banner/banner03.jpg" mode="aspectFill" />
    </view>
    <!-- 商品列表，一行两个，支持懒加载 -->
    <view class="goods-list">
      <view class="goods-row" v-for="(row, rowIdx) in goodsRows" :key="rowIdx">
        <view class="goods-card" v-for="(item, idx) in row" :key="idx" @click="goToDetail(item.id)">
          <image :src="item.img" class="goods-img" />
          <view class="goods-info">
            <view class="goods-tags">
              <text v-for="(tag, tIdx) in item.tags" :key="tIdx" :class="'goods-tag ' + tag.type">{{ tag.text }}</text>
            </view>
            <view class="goods-title">{{ item.title }}</view>
            <view class="goods-desc">{{ item.desc }}</view>
            <view class="goods-bottom">
              <view class="goods-price-line">
                <text class="price">￥{{ item.price }}</text>
              </view>
              <button class="buy-btn">立即抢</button>
            </view>
          </view>
        </view>
      </view>
      <!-- 加载中和无更多提示 -->
      <view v-if="loading" class="loading-text">加载中...</view>
      <view v-if="finished" class="finished-text">没有更多了</view>
    </view>
    <!-- 底部导航栏已移除，如需可自行添加 -->

    <!-- 返回顶部按钮 -->
    <view
      v-if="showBackTop"
      class="back-top-btn"
      @click="scrollToTop"
    >
    <image src="/static/images/返回顶端.png" style="width:24px;height:24px;" />
    </view>
  </view>
</template>

<script>

import { list, getParentTypeList } from '@/api/index'
export default {
  data() {
    return {
      showBackTop: false,
      categories: [], // 商品分类列表（从后端获取）
      activeCategory: null, // 当前选中的类型id（用于高亮）
      typeId: null,         // 当前选中的类型id（用于商品查询）
      goodsList: [],        // 商品列表
      pageNum: 1,           // 当前页码
      pageSize: 10,         // 每页数量
      total: 0,             // 商品总数
      loading: false,       // 是否正在加载
      finished: false,      // 是否已加载全部
      bannerList: [
        '/static/images/banner/banner01.jpg',
        '/static/images/banner/banner02.jpg',
        '/static/images/banner/banner03.jpg'
      ]
    }
  },
  created() {
    // 页面创建时，先获取分类，再加载商品
    this.getCategories();
    this.loadGoodsList();
  },
  onReachBottom() {
    // 页面滚动到底部时自动加载下一页
    this.loadGoodsList();
  },
  onPullDownRefresh() {
    // 下拉刷新时重置商品列表和分页
    this.pageNum = 1;
    this.goodsList = [];
    this.finished = false;
    this.loadGoodsList().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  onPageScroll(e) {
    // 滚动距离大于300px时显示返回顶部按钮
    this.showBackTop = e.scrollTop > 300;
  },
  computed: {
    goodsRows() {
      // 将商品列表每两个分为一组，用于一行显示两个商品
      const rows = []
      for (let i = 0; i < this.goodsList.length; i += 2) {
        rows.push(this.goodsList.slice(i, i + 2))
      }
      return rows
    }
  },
  methods: {
    // 获取商品分类列表
    async getCategories() {
      try {
        console.log('开始获取分类列表...');
      const res = await getParentTypeList();
        console.log('分类列表响应：', res);

      this.categories = res.data || res;
        console.log('分类数据：', this.categories);

      if (this.categories.length > 0) {
        // 默认选中第一个分类
          this.activeCategory = this.categories[0].id;
          this.typeId = this.categories[0].id;
          console.log('默认选中分类：', this.activeCategory);
        }
      } catch (e) {
        console.error('获取分类列表失败：', e);
        // 如果API调用失败，使用模拟数据
        this.categories = [
          { id: 1, categoryName: '电子产品', categoryIcon: '/static/images/logo.png' },
          { id: 2, categoryName: '服装', categoryIcon: '/static/images/logo.png' },
          { id: 3, categoryName: '家居用品', categoryIcon: '/static/images/logo.png' },
          { id: 4, categoryName: '食品饮料', categoryIcon: '/static/images/logo.png' }
        ];
        this.activeCategory = this.categories[0].id;
        this.typeId = this.categories[0].id;
      }
    },
    // 加载商品列表，支持分页和懒加载
    loadGoodsList() {
      return new Promise(async (resolve) => {
        if (this.loading || this.finished) return resolve();
        this.loading = true;
        try {
          // 组装查询参数，带上typeId
          const params = { pageNum: this.pageNum, pageSize: this.pageSize };
          if (this.typeId) params.typeId = this.typeId;
          console.log('加载商品列表，参数：', params);

          const res = await list(params);
          console.log('商品列表响应：', res);

          const records = res.rows || [];
          console.log('商品记录数：', records.length);

          // 拼接新数据到商品列表
          this.goodsList = this.goodsList.concat(records.map(item => ({
            img: item.imgUrl, // 商品图片
            title: item.goodsName, // 商品名称
            desc: item.introduce,  // 商品描述
            price: item.price,     // 现价
            originPrice: item.originPrice || '', // 原价
            tags: item.tagName
              ? item.tagName.split(',').map(tag => ({ text: tag, type: 'green' }))
              : [],
            id: item.id,           // 商品id
            sales: item.sales || 0 // 销量
          })));

          console.log('当前商品列表长度：', this.goodsList.length);

          this.total = res.total || 0;
          // 判断是否加载完全部
          if (this.goodsList.length >= this.total) {
            this.finished = true;
          } else {
            this.pageNum++;
          }
        } catch (e) {
          console.error('加载商品列表失败：', e);
          // 如果API调用失败，使用模拟数据
          this.goodsList = [
            {
              img: '/static/images/banner/banner01.jpg',
              title: '苹果 iPhone 15 Pro',
              desc: '最新款iPhone，性能强劲',
              price: 7999,
              originPrice: 8999,
              tags: [{ text: '热销', type: 'red' }, { text: '新品', type: 'green' }],
              id: 1,
              sales: 1000
            },
            {
              img: '/static/images/banner/banner02.jpg',
              title: '华为 Mate 60 Pro',
              desc: '国产旗舰，拍照出色',
              price: 6999,
              originPrice: 7999,
              tags: [{ text: '推荐', type: 'orange' }],
              id: 2,
              sales: 800
            }
          ];
          this.finished = true;
        }
        this.loading = false;
        resolve();
      });
    },

	toSecKill(){
	   uni.navigateTo({ url: `/pages/seckill/activity`});
	},
    // 跳转到商品详情页
    goToDetail(id) {
      uni.navigateTo({ url: `/pages/product/detail?id=${id}`});
    },
    // 分类点击事件，切换分类并重置商品列表
    onCategoryClick(item) {
      // 存储要跳转的分类id
      uni.setStorageSync('category_jump_id', item.id);
      // 跳转到分类页面
      uni.switchTab ({url: `/pages/category/index`});
    },
	 goToCouponCenter() {
	      uni.navigateTo({
	        url: '/pages/coupon-center/index'
	      })
	},
    goToSearch() {
      uni.navigateTo({ url: '/pages/search/index'  });
    },
    scrollToTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    },
    goToAddress() {
      uni.navigateTo({ url: '/pages/address/index' });
    },
  }
}
</script>

<style scoped>
/* 顶部地址栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 12px 8px 12px;
  background: #fff;
  font-size: 15px;
  color: #333;
  border-bottom: 1px solid #f2f2f2;
}
.location {
  flex: 1;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.top-icons {
  display: flex;
  gap: 12px;
  color: #999;
  font-size: 20px;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  background: #f7f7f7;
  border-radius: 22px;
  padding: 0 16px;
  height: 40px;
  margin: 16px 12px 0 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}
.search-input {
  flex: 1;
  height: 32px;
  border: none;

  border-radius: 16px;
  padding: 0 12px;
  margin-right: 8px;
  background: transparent;
  font-size: 15px;
  color: #333;
  margin-left: 8px;
}
.search-btn {
  background: #ff6700;
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 0 18px;
  height: 32px;
  font-size: 14px;
  margin-left: 8px;
  transition: background 0.2s;
}
.search-btn:active {
  background: #ff4d4f;
}
.member-code {
  color: #ff6700;
  font-size: 13px;
  font-weight: bold;
}

/* 轮播图 */
.swiper-box {
  margin: 18px 18px 0 18px;
  border-radius: 18px;
  overflow: hidden;
  height: 130px;
}
.swiper-img {
  width: 100%;
  height: 130px;
  object-fit: cover;
  border-radius: 18px;
}

/* 分类入口 */
.category-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 16px 12px 0 12px;
  margin-bottom: 8px;
}
.category-item {
  width: 22%;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: box-shadow 0.2s, background 0.2s;
}
.category-item:hover {
  box-shadow: 0 2px 8px rgba(255,103,0,0.06);
  background: #fff7f0;
  transition: box-shadow 0.2s, background 0.2s;
}
.category-item:hover {
  box-shadow: 0 2px 8px rgba(255,103,0,0.06);
  background: #fff7f0;
}
.category-item.active {
  border: 2px solid #ff6700;
  background: #fff7f0;
}
.category-img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #f5f5f5;
  margin-bottom: 6px;
}
.category-text {
  font-size: 13px;
  color: #333;
  margin-top: 0;
  line-height: 1.2;
}

/* banner 区域 */
.banner-area, .night-area {
  margin: 0 12px 12px 12px;
  border-radius: 10px;
  overflow: hidden;
  height: 70px;
}
.banner-img, .night-img {
  width: 100%;
  height: 70px;
  object-fit: cover;
}

/* 商品列表 */
.goods-list {
  padding: 0 10px 20px 10px;
  flex: 1;
}
.goods-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 18px;
}
.goods-card {
  width: 48%;
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  margin-bottom: 18px;
}
.goods-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 16px 16px 0 0;
}
.goods-info {
  flex: 1;
  padding: 10px 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.goods-tags {
  margin-bottom: 4px;
}
.goods-tag {
  display: inline-block;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 8px;
  margin-right: 4px;
  margin-bottom: 2px;
  color: #fff;
}
.goods-tag.green { background: #4caf50; }
.goods-tag.red { background: #f44336; }
.goods-tag.orange { background: #ff9800; }
.goods-tag.gold { background: #ffd700; color: #333; }
.goods-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 2px;
  color: #222;
}
.goods-desc {
  font-size: 12px;
  color: #888;
  margin-bottom: 6px;
}
.goods-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.goods-price-line {
  display: flex;
  align-items: baseline;
  gap: 6px;
}
.price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
  margin-right: 6px;
}
.origin-price {
  color: #bbb;
  font-size: 12px;
  text-decoration: line-through;
}
.buy-btn {
  background: linear-gradient(90deg, #ffb3b3 0%, #ff4d4f 100%);
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 0 16px;
  height: 32px;
  font-size: 14px;
  margin-left: 8px;
}
/* 商品列表 */
.goods-list {
  padding: 0 10px 70px 10px;
}
.goods-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 18px;
}
.goods-card {
  width: 48%;
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  margin-bottom: 18px;
}
.goods-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 16px 16px 0 0;
}
.goods-info {
  flex: 1;
  padding: 10px 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.goods-tags {
  margin-bottom: 4px;
}
.goods-tag {
  display: inline-block;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 8px;
  margin-right: 4px;
  margin-bottom: 2px;
  color: #fff;
}
.goods-tag.green { background: #4caf50; }
.goods-tag.red { background: #f44336; }
.goods-tag.orange { background: #ff9800; }
.goods-tag.gold { background: #ffd700; color: #333; }
.goods-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 2px;
  color: #222;
}
.goods-desc {
  font-size: 12px;
  color: #888;
  margin-bottom: 6px;
}
.goods-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.goods-price-line {
  display: flex;
  align-items: baseline;
  gap: 6px;
}
.price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
  margin-right: 6px;
}
.origin-price {
  color: #bbb;
  font-size: 12px;
  text-decoration: line-through;
}
.buy-btn {
  background: linear-gradient(90deg, #ffb3b3 0%, #ff4d4f 100%);
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 0 16px;
  height: 32px;
  font-size: 14px;
  margin-left: 8px;
}

/* 底部导航栏 */
.tabbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 56px;
  background: #fff;
  display: flex;
  border-top: 1px solid #eee;
  z-index: 100;
}
.tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 12px;
  padding-top: 4px;
}
.tabbar-item.active {
  color: #ff6700;
}
.tabbar-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 2px;
}

.home-container {
  background: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 56px;
  padding-top: 24px;
  padding-top: 24px;
  /* 移除底部padding，让内容可以完全显示 */
  padding-bottom: 20px;
  /* 确保页面可以正常滚动 */
  overflow-y: auto;
  /* 设置页面容器为flex布局 */
  display: flex;
  flex-direction: column;
}

.loading-text {
  text-align: center;
  color: #888;
  padding: 10px 0;
}
.finished-text {
  text-align: center;
  color: #bbb;
  padding: 10px 0;
}

.back-top-btn {
  position: fixed;
  right: 24px;
  bottom: 100px;
  width: 44px;
  height: 44px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  font-size: 24px;
  color: #ff6700;
}

</style>
